import axios from 'axios'
import store from '../store'
import router from '../router'
import * as types from '../store/types'
import account from './modules/account'
import company from './modules/company'
import shop from './modules/shop'
import category from './modules/category'
import task from './modules/task'
import user from './modules/user'
import XunDianShuJu from './modules/xun_dian_shu_ju'
import banner from './modules/banner'
import notification from './modules/notification'
import role from './modules/role'
import report from './modules/report'
import permission from './modules/permission'
import dashboard from './modules/dashboard'

axios.defaults.baseURL = process.env.API_URL;
axios.defaults.timeout = process.env.TIMEOUT;

/**
 * 定义请求拦截器
 */
axios.interceptors.request.use(config => {
	const access_token = store.state.account.access_token;

	if (access_token) {
		config.headers.Authorization = `Bearer ${access_token}`;
	}
	return config;
}, error => {
	return Promise.reject(error);
});

/**
 * 定义响应拦截器
 */
axios.interceptors.response.use(response => {
	return response;
}, error => {
	if (error.response) {
		if (error.response.config.url === '/api/auth/login') {
			return Promise.reject(error);
		}
		switch (error.response.status) {
			case 401:
				/**
				 * 返回 401 清除token信息并跳转到登录页面
				 */
				store.commit(types.SET_USER);
				store.commit(types.SET_ACCESS_TOKEN);
				router.replace({
					path: '/login',
					// query: {redirect: router.currentRoute.fullPath}
					// query: { redirect: to.fullPath }
				});
				break;
			default:
				return Promise.reject(error);
		}
	}
});

/**
 * 导出API
 */
export default {
	account,
	company,
	shop,
	category,
	task,
	user,
	XunDianShuJu,
	banner,
	notification,
	role,
	report,
	permission,
	dashboard
}
